<template>
  <div class="resources-view">
    <!-- 统一导航栏 -->
    <NavBar @toggle-sidebar="toggleSidebar" />
    
    <div class="resources-container">
      <!-- 主内容区 -->
      <div class="main-content">
        <!-- 顶部栏简化，只保留标题 -->
        <div class="top-bar">
          <h2>教学资源库</h2>
          <button
              class="generate-btn"
              @click="backToHome"
          >
            返回
          </button>
        </div>

        <!-- 搜索和筛选栏 -->
        <div class="filter-bar">
          <div class="filter-group">
            <label>类型：</label>
            <el-select v-model="selectedType" placeholder="全部" class="filter-select">
              <el-option v-for="type in typeOptions" :key="type" :label="type" :value="type" />
            </el-select>
          </div>

          <div class="search-group">
            <el-input
                v-model="searchKeyword"
                placeholder="搜索资源名称..."
                @input="searchResources"
                style="width: 300px"
            >
              <template #append>
                <el-button @click="searchResources">搜索</el-button>
              </template>
            </el-input>
          </div>

          <el-button @click="resetFilters">重置</el-button>
          <span class="total-count">共 {{ totalResourcesCount }} 个资源</span>
        </div>

        <!-- 资源列表 -->
        <div class="resources-list">
          <div
              v-for="resource in filteredResources"
              :key="resource.id"
              class="resource-card"
          >
            <div class="resource-icon">
              <el-icon v-if="resource.type === '文档'"><Document /></el-icon>
              <el-icon v-else-if="resource.type === '视频'"><VideoCamera /></el-icon>
              <el-icon v-else-if="resource.type === '图片'"><Picture /></el-icon>
              <el-icon v-else-if="resource.type === '语音'"><Microphone /></el-icon>
              <el-icon v-else><FolderOpened /></el-icon>
            </div>

            <div class="resource-info">
              <div class="resource-name">{{ resource.name }}</div>

              <div class="resource-tags">
                <span
                    class="type-tag"
                    :style="{ background: resource.typeColor, color: resource.typeTextColor }"
                >
                  {{ resource.type }}
                </span>
              </div>

              <div class="resource-meta">
                <span>创建: {{ resource.createDate }}</span>
              </div>

              <div class="resource-actions">
                <el-button size="small" @click="previewResource(resource.ossUrl)">预览</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog
        v-model="previewVisible"
        title="资源预览"
        width="80%"
        top="5vh"
        :before-close="handlePreviewClose"
        class="custom-preview-dialog"
    >
      <template v-if="previewUrl">
        <!-- 图片 -->
        <img
            v-if="isImage(previewUrl)"
            :src="previewUrl"
            alt="预览图片"
            class="image-preview"
        />

        <!-- PDF / Office -->

        <!-- 视频 -->
        <video
            v-else-if="isVideo(previewUrl)"
            :src="previewUrl"
            controls
            class="media-preview"
        />

        <!-- 音频 -->
        <audio
            v-else-if="isAudio(previewUrl)"
            :src="previewUrl"
            controls
            class="audio-preview"
        />


        <!-- 其他（不支持的格式） -->
        <div v-else class="unsupported-box">
          <p>该文件格式暂不支持预览</p>
          <el-button type="primary" @click="downloadResource(previewUrl)">下载资源</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, computed, onMounted} from 'vue'
import { useRouter } from 'vue-router';
import { getAiResourcesListAPI, selectResourcesAPI} from '@/apis/index.ts'
import {ElMessage, ElMessageBox} from "element-plus";
import { Document, VideoCamera, Picture, Microphone,FolderOpened } from '@element-plus/icons-vue'
import NavBar from '@/components/NavBar.vue'

// 侧边栏状态
const sidebarCollapsed = ref(false)

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

interface Resource {
  resourceId: number
  chatId: number
  userId: number
  ossUrl: string
  type: string
  createdAt: string | Date | any
  title: string
}
// UI 展示用的封装后的资源类型
interface DisplayResource {
  id: number
  name: string
  ossUrl: string
  type: string
  typeColor: string
  typeTextColor: string
  createDate: string
}

const resources = ref<DisplayResource[]>([])

const router = useRouter()

const activeTab = ref('myResources')
const selectAll = ref(false)
const selectedResources = ref<number[]>([])
const searchKeyword = ref('')
const selectedType = ref('全部')
const selectedStatus = ref('全部')

const typeOptions = ['全部', '文档', '视频', '图片','语音']

//获取资源列表
const fetchResources = async () => {
  try {
    const userId = Number(localStorage.getItem('id')||1)
    const res = await getAiResourcesListAPI(userId)
    if (res.code === 200 && Array.isArray(res.data)) {
      resources.value = res.data.map((item): DisplayResource => {
        const typeColorMap = {
          文档: '#E0E7FF',
          视频: '#FEF3C7',
          图片: '#c5ffe6',
          语音: '#F3F4F6'
        }
        const typeTextColorMap = {
          文档: '#3730A3',
          视频: '#92400E',
          图片: '#12451d',
          语音: '#111827'
        }

        let createDate = '未知'
        if (item.createdAt) {
          if (typeof item.createdAt === 'string') {
            createDate = (item.createdAt as string).slice(0, 10)
          } else {
            const date = new Date(item.createdAt as any)
            if (!isNaN(date.getTime())) {
              createDate = date.toISOString().slice(0, 10)
            }
          }
        }

        return {
          id: item.resourceId,
          name: item.title,
          ossUrl: item.ossUrl,
          type: item.type,
          typeColor: typeColorMap[item.type as keyof typeof typeColorMap] || '#E5E7EB',
          typeTextColor: typeTextColorMap[item.type as keyof typeof typeTextColorMap] || '#000000',
          createDate
        }
      })
    } else {
      console.error('获取资源失败:', res.message)
      ElMessage.error('获取资源失败')
    }
  } catch (error) {
    console.error('获取资源失败:', error)
    ElMessage.error('获取资源失败')
  }
}

// 筛选后的资源
const filteredResources = computed(() => {
  let filtered = resources.value

  // 按类型筛选
  if (selectedType.value !== '全部') {
    filtered = filtered.filter(r => r.type === selectedType.value)
  }

  // 按搜索关键词筛选
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(r =>
        r.name.toLowerCase().includes(keyword)
    )
  }

  return filtered
})

// 总资源数量
const totalResourcesCount = computed(() => filteredResources.value.length)

// 搜索资源
const searchResources = () => {
  // filteredResources 会自动更新
}

// 重置筛选
const resetFilters = () => {
  searchKeyword.value = ''
  selectedType.value = '全部'
  selectedStatus.value = '全部'
}

// 预览相关
const previewVisible = ref(false)
const previewUrl = ref('')

// 预览资源
const previewResource = (url: string) => {
  previewUrl.value = url
  previewVisible.value = true
}

// 关闭预览
const handlePreviewClose = () => {
  previewVisible.value = false
  previewUrl.value = ''
}

// 文件类型判断函数
const isImage = (url: string) => {
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
  return imageExtensions.some(ext => url.toLowerCase().includes(ext))
}

const isVideo = (url: string) => {
  const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm']
  return videoExtensions.some(ext => url.toLowerCase().includes(ext))
}

const isAudio = (url: string) => {
  const audioExtensions = ['.mp3', '.wav', '.ogg', '.aac', '.flac']
  return audioExtensions.some(ext => url.toLowerCase().includes(ext))
}

const isPDF = (url: string) => {
  return url.toLowerCase().includes('.pdf')
}

const isOfficeDoc = (url: string) => {
  const officeExtensions = ['.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx']
  return officeExtensions.some(ext => url.toLowerCase().includes(ext))
}

const getOfficeViewerUrl = (url: string) => {
  return `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(url)}`
}

// 下载资源
const downloadResource = (url: string) => {
  window.open(url, '_blank')
}

onMounted(() => {
  fetchResources()
})

const backToHome = () => {
  router.push('/teacher-home')
}
</script>

<style scoped>
.resources-view {
  min-height: 100vh;
  background: linear-gradient(180deg, #E2E8F0 0%, #F8FAFC 100%);
  font-family: 'Inter', sans-serif;
  display: flex;
  flex-direction: column;
}

.resources-container {
  flex: 1;
  min-height: calc(100vh - 64px); /* 减去NavBar的高度64px */
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  padding: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.top-bar {
  position: sticky;
  top: 0;
  z-index: 10;
  background: white;
  border-bottom: 1px solid #E5E7EB;
  padding: 25px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.top-bar h2 {
  font-size: 24px;
  font-weight: 600;
  color: #1F2937;
  margin: 0;
}

.filter-bar {
  padding: 20px 24px;
  display: flex;
  align-items: center;
  gap: 20px;
  background: white;
  border-bottom: 1px solid #E5E7EB;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  white-space: nowrap;
}

.search-group {
  flex: 1;
  max-width: 300px;
}

.resources-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  padding: 24px; /* 增加内边距 */
  box-sizing: border-box; /* 确保padding不会影响宽度计算 */
  overflow-y: auto;
  max-height: calc(100vh - 170px);
}

/* 资源卡片样式改为习题卡片风格 */
.resource-card {
  background: white;
  border: 1px solid #E5E7EB;
  border-radius: 12px;
  padding: 24px;
  transition: all 0.2s;
  display: flex;
  gap: 16px;
  cursor: pointer;
}

.resource-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: transparent;
}

/* 图标部分 */
.resource-icon {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #F3F4F6;
  border-radius: 10px;
  color: #6B7280;
  font-size: 24px;
}

/* 资源信息 */
.resource-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.resource-name {
  font-size: 16px;
  font-weight: 600;
  color: #1F2937;
  line-height: 1.4;
  margin-bottom: 4px;
}

.resource-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.type-tag {
  padding: 4px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  color: inherit; /* 颜色通过内联样式控制 */
}

.resource-meta {
  font-size: 14px;
  color: #6B7280;
}

.resource-actions {
  margin-top: auto;
  display: flex;
  gap: 8px;
}

.generate-btn {
  background: #F3F4F6;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 15px;
  font-weight: 500;
  color: #9CA3AF;
  cursor: pointer;
  transition: all 0.2s;
}

.generate-btn:not(:disabled) {
  background: #1F2937;
  color: white;
}

.generate-btn:not(:disabled):hover {
  background: #374151;
}

/* Element Plus 样式覆盖 */
:deep(.el-select) {
  width: 120px;
}

:deep(.el-input) {
  width: 220px;
}

:deep(.el-button) {
  height: 38px;
}

/* 总资源数量样式 */
.total-count {
  margin-left: auto;
  font-size: 14px;
  color: #6B7280;
  font-weight: 500;
  padding: 8px 12px;
  background: white;
  border-bottom: 1px solid #E5E7EB;
}

/* 预览框样式与习题库风格保持一致 */
:deep(.custom-preview-dialog .el-dialog__body) {
  padding: 20px;
  background-color: #f9f9f9;
}

.media-preview {
  width: 100%;
  max-height: 600px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
}

.audio-preview {
  width: 100%;
  margin-top: 10px;
}

.unsupported-box {
  text-align: center;
  padding: 24px;
}

.unsupported-box p {
  margin-bottom: 16px;
  font-size: 16px;
  color: #666;
}

.image-preview {
  display: block;
  max-width: 100%;
  height: auto;
  object-fit: contain;
  margin: 0 auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .resources-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
  }

  .filter-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .filter-group {
    justify-content: space-between;
  }
}

</style>
